package com.jinzheng.qhwocket.commont;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.buf.HexUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;

/**
 * socket接受客户端线程
 */
public class ServerReceiveThreadTest implements Runnable {

    private Socket socket;

    private static Logger log = LoggerFactory.getLogger(ServerReceiveThreadTest.class);

    public ServerReceiveThreadTest(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run(){
        try {
            socket.setSoTimeout(10);//设置socket读超时时间10毫秒
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int value = inputStream.read(bytes);
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            out.write(bytes,0,value);
            socket.shutdownInput();
            byte[] toByteArray = out.toByteArray();
            System.out.println("接受服务器字节数据："+toByteArray);
            String finalValue = new SetInitProducerMessage(bytes, value).invoke();
            System.out.println("socket服务端最终数据发送kafka数据格式："+finalValue);
            if(StringUtils.isNotBlank(finalValue)){
                KafkaProducer kafkaProducer = SpringUtil.getBean(KafkaProducer.class);
                kafkaProducer.sendMessageByTopic("tesdsea",null, JSONObject.toJSONString(finalValue, SerializerFeature.WriteMapNullValue,SerializerFeature.WriteDateUseDateFormat));
            }
            log.info("客户端传来的数据："+new String(bytes,0,value, StandardCharsets.UTF_8));
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write(bytes,0,value);
            log.info("服务端关闭客户端[{}]", socket.getRemoteSocketAddress());
            outputStream.close();
            outputStream.close();
            socket.close();
        } catch (Exception e) {
            log.info("接收数据异常socket关闭");
            e.printStackTrace();
        } finally {
            log.info("数据要怎么保留");
        }

    }

    /**
     * 十六进制转十进制
     * @param content
     * @return
     */
    public static int covert(String content){
        int number=0;
        String [] HighLetter = {"A","B","C","D","E","F"};
        Map<String,Integer> map = new HashMap<>();
        for(int i = 0;i <= 9;i++){
            map.put(i+"",i);
        }
        for(int j= 10;j<HighLetter.length+10;j++){
            map.put(HighLetter[j-10],j);
        }
        String[]str = new String[content.length()];
        for(int i = 0; i < str.length; i++){
            str[i] = content.substring(i,i+1);
        }
        for(int i = 0; i < str.length; i++){
            number += map.get(str[i])*Math.pow(16,str.length-1-i);
        }
        return number;
    }


    /**
     * 数据校验
     * @param bytes
     * @return
     */
    public static boolean checkCode(byte[] bytes){
        if(null==bytes || bytes.length < 25 || bytes[0]!=0x23 || bytes[1]!=0x23){
            log.warn("数据格式错误：{}",HexUtils.toHexString(bytes));
            return false;
        }
        byte checkCode = 0x00;
        for (byte bt:bytes){
            checkCode ^= bt;
        }
        if(checkCode!=0x00){
            log.warn("数据校验错误：{}",HexUtils.toHexString(bytes));
            return false;
        }
        return true;
    }

    private static byte[] stringToByte (String strings) {
        byte[] result=new byte[strings.length()/2];
        for (int i = 0; i <= strings.length(); i += 2) {
            result[i/2]=(byte) (charToInt(strings.charAt(i))*16+charToInt(strings.charAt(i+1)));
        }
        return result;
    }
    private static int charToInt(char ch) {
        if (ch >= 65 && ch <= 70) {
            return ch - 55;
        } else if (ch >= 97 && ch <= 102) {
            return ch - 87;
        } else {
            return ch;
        }
    }

    public static void main(String[] args) {
        String value = "232301FE393031323835303730303030303030303001001E160C0F0B061B000438393836303242363033313730303230313830340100A5";
        byte[] stringToByte = stringToByte(value);
        boolean checkCode = checkCode(stringToByte);
        System.out.println(checkCode);
    }

    /**
     * 处理socket客户端发送的数据
     */
    private class SetInitProducerMessage {
        private byte[] bytes;
        private int value;

        public SetInitProducerMessage(byte[] bytes, int value) {
            this.bytes = bytes;
            this.value = value;
        }

        public String invoke() {
            String socketValue = new String(bytes, 0, value, StandardCharsets.UTF_8);
            String substring0x = socketValue.substring(44, 48);
            int subCount=covert(substring0x);
            String substringStart = StringUtils.substring(socketValue,49,(48+subCount*2));
            String reverse = StringUtils.reverse(socketValue);
            String substringReverse = reverse.substring(0, 2);
            return substringStart + StringUtils.reverse(substringReverse);
        }
    }
}
